/**
 * Created by fsy on 14-10-9.
 */

function Se(){
    var S = this;
    this.default = {
        timeout:  15000,
        sid:      '00000000000000000000000000000000',
        isLogin:false
    };
    this.id = 0;
    this.option = {};
    this.start = true;
    this.init  = function(){
        this.option = this.default;
        var sids = S.checkLogin();
        if(!sids || sids == undefined || sids == "undefined" || sids == ""){
            this.layout.login();
        }else{
            //S.isLogout();
            this._init();
        }
    };

     this.myrefresh=function(){
	window.location.reload(true);
};

    this._init = function(){
        this.start = false;
        this.option.sid = S.checkLogin();
        S.option.isLogin = true;
        S.setIntval();
        this.layout.bar();
        this.layout.show();
    };

    this._call = function(req, cb)
    {
        return $.ajax('/ubus', {
            cache:       false,
            contentType: 'application/json',
            data:        JSON.stringify(req),
            dataType:    'json',
            type:        'POST',
            timeout:     S.default.timeout,
            _rpc_req:   req,
        }).then(cb, cb);
    };

    this.setIntval = function(){
        S.intvalint = setInterval(function(){
            S.getId();
            var reg ={
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'session','access',{scope:'ubus', object:'session', function:'access'}]
            };
            S._call(reg,function(data){
//                if(data){
//                    if(typeof data.result != undefined && typeof data.result != "undefined"){
//                        if(data.result[0] == 0){
//                            var returndata = data.result[1];
//                            S.tools.setCookie('sid', S.option.sid,S.option.timeout);
//                            S.tools.setCookie('isLogin', 1);
//                        }
//                    }else{
//                        S.option.isLogin = false;
//                        //S.tools.setCookie('isLogin', 0);
//                        //S.onReadre.logout();
//                    }
//                }else{
//                    S.option.isLogin = false;
//                    //S.tools.setCookie('isLogin', 0);
//                }

            });
        },14000);
    };
    this.clearIntval = function(ids){
        clearInterval(ids);
    };

    this.checkDeviceLine = function(){
        S.getId();
        var reg ={
            id: S.id,
            jsonrpc:'2.0',
            method:"call",
            params:[S.option.sid,'iwinfo','info',{device:'wlan0'}]
        };
        $.ajax('/ubus', {
            cache:       false,
            contentType: 'application/json',
            data:        JSON.stringify(reg),
            dataType:    'json',
            type:        'POST',
            timeout:     S.default.timeout,
            _rpc_req:   reg,
            error:function(){
                S.option = {};
                S.cookieUtil.unset('sid');
                S.cookieUtil.unset('isLogin');
                S.layout.login();
            },
            async:false,
            success:function(data){
                if((typeof data.result == "object")){
                    console.log("checkDeviceLine success object");
                    S.option.isLogin = true;
                }else{
                    S.option = {};
                    S.cookieUtil.unset('sid');
                    S.cookieUtil.unset('isLogin');
                    S.layout.login();
                }
            }
        });

    };

    this.isLogout =function(){
        this.checkDeviceLine();
    };

    this.checkLogin = function(){
        var sid = S.cookieUtil.get('sid');
        if(sid) S.option.isLogin = true;
        return sid;
    };

    this.getId = function(){
        return this.id++;
    };

    this.layout = {
        login:function(){
            var str = S.tools.heredoc(function(){
            /*
             <div class="login_bg">
             <div class="login_bgs"></div>
             <div class="login_logo">
             <div class="login_box">
             <div class="login_h">
             <span>远程模块登录</span>
             <b>测试版本</b>
             </div>
             <div class="forms">
             <div class="login_in">用户名：<input type="text" maxlength="16" name="username" id="username" value="" /></div>
             <div class="login_in">密 码 ：<input type="password" maxlength="16" name="passm" id="passm" value="" /></div>
             <button id="loginButton"><a href="javascript:;">登录</a></button>

             </div>

             </div>
             </div>

             </div>
             */
            });
            $('body').html(str);
            S.clearIntval();
            S.cookieUtil.unset('sid');
            S.tools.setCookie('isLogin', 0);
            S.regEvent.doLoginCheck();
        },
        show:function(){

            if(typeof S.option.configs == "undefined" || typeof S.option.configs == undefined );
		alert("config is null");
		 S.option.configs = {};
            var str = S.tools.heredoc(function(){
            /*
             <div class="con">
             <h3>设备状态：</h3>
             <div class="con_li"><span>设备名称：</span><b id="rotu_name"></b></div>
             <div class="con_li"><span>LAN口IP：</span><b id="lan_ip"></b></div>
             <div class="con_li"><span>WAN口MAC：</span><b id="mac"></b></div>
		 <div class="con_li"><span>WIFI类型：</span><b id="wifi_status"></b></div>
		
             <div class="con_li"><span>WIFI名称：</span><b id="ssid"></b></div>
             <div class="con_li"><span>WIFI密码：</span><b id="wifi_passwd"></b></div>
		<div class="con_li"><span>配对设备ID：</span><b id="hulian_id"></b></div>
		 <div class="con_li"><span>互连状态：</span><b id="hlzts"></b></div>

		</div>
             <div class="con">
             <h3>Wan口状态：</h3>     


             <div class="con_li">
                <span>WAN口接入类型：</span><b id="wan_state"></b>
             </div>
             <div id="wan_state_waninfos">
		</div>


             
             <!--<div class="con_li">
                <span>WWAN DHCP状态：</span><b id="wwan_dhcp_state"></b>
             </div>-->
             <div id="wwan_state_wwaninfos">
             </div>

		<div class="con_li_b"><button id="flash"><a href="javascript:;">刷新</a></button></div>


             */


            });


	

		function showTime(){

		document.getElementById('rotu_name').innerHTML = '1';
            setTimeout(showTime, 5000);}

            $('#content').html(str);
            S.onReadre.init();


				
		$("#flash").click(function(){
                //S.onReadre.reboot();
		location.reload(true);
            });


        },
        setpass:function(){
            var str = S.tools.heredoc(function(){
            /*
             <div class="con">
             <h3>登录密码修改：</h3>
             <div class="con_li"><span>新密码：</span><b><input id="spd" type="password"  value=""/></b></div>
             <div class="con_li"><span>重复密码：</span><b><input id="rspd" type="password"  value=""/></b></div>
             <div class="con_li_b"><button id="pmd"><a href="javascript:;">确认修改</a></button></div>
             <div class="con_li_b"><button id="rest"><a href="javascript:;">重启</a></button></div>
             </div>
             */
            });
            $('#content').html(str);
            $("#pmd").click(function(){
                S.isLogout();
                S.onReadre.setpm();
            });
            $("#rest").click(function(){
                S.onReadre.reboot();
            });
        },
        setting:function(){
            if(S.option.configs.wanStauts !== undefined && (S.option.configs.wanStauts.proto == "dhcp")) {
                var str = S.tools.heredoc(function(){
                /*

                 <div class="con">
                 <div class="con_li"></div>
                 <div class="con_li">
                    <span>连接类型：</span>
                        <b>
                            <select id="wan_proto" style="height:30px; margin-top:5px; width:200px;">
                                 <option value="static">静态IP(手动获取)</option>
                                 <option value="dhcp" selected="selected">自动获取IP(DHCP)</option>
                                 <option value="pppoe">PPPOE(虚拟拨号)</option>
                            </select>
                        </b>
                 </div>

                 <div id="wanStauts_content">
                 </div>

                 <div class="con_li_b"><button id="settingbutton"><a href="javascript:;">保存</a></button></div>
                 */
                });
                $('#content').html(str);

            }else if(S.option.configs.wanStauts.proto == "static"){
                var str = S.tools.heredoc(function(){
                    /*
                     <div class="con">
                     <div class="con_li"></div>
                     <div class="con_li">
                     <span>连接类型：</span>
                     <b>
                     <select id="wan_proto" style="height:30px; margin-top:5px; width:200px;">
                     <option value="static" selected="selected">静态IP(手动获取)</option>
                     <option value="dhcp" >自动获取IP(DHCP)</option>
                     <option value="pppoe">PPPOE(虚拟拨号)</option>
                     </select>
                     </b>
                     </div>
                    <div id="wanStauts_content">
                     <div class="con_li">
                     <span>IP地址：</span>
                     <b >
                     <input type="text" name="network_static_ip" id="network_static_ip" />
                     </b>
                     </div>
                     <div class="con_li">
                     <span>子网掩码：</span>
                     <b>
                     <input type="text" name="network_static_netmask" id="network_static_netmask" />
                     </b>
                     </div>
                     <div class="con_li">
                     <span>网关地址：</span>
                     <b >
                     <input type="text" name="network_static_gatewa" id="network_static_gatewa" />
                     </b>
                     </div>
                     <div class="con_li">
                     <span>首选dns：</span>
                     <b >
                     <input type="text" name="network_static_dns1" id="network_static_dns1" />
                     </b>
                     </div>
                     <div class="con_li">
                     <span>备用dns：</span>
                     <b >
                     <input type="text" name="network_static_dns2" id="network_static_dns2" />
                     </b>
                     </div>
                     </div>
                     <div class="con_li_b"><button id="settingbutton"><a href="javascript:;">保存</a></button></div>
                     */
                });
                $('#content').html(str);
                if(typeof(S.option.configs.wanStauts.ipaddr) != "undefined") $("#network_static_ip").val(S.option.configs.wanStauts.ipaddr);
                if(typeof(S.option.configs.wanStauts.netmask) != "undefined")$("#network_static_netmask").val(S.option.configs.wanStauts.netmask);
                if(typeof(S.option.configs.wanStauts.gateway) != "undefined")$("#network_static_gatewa").val(S.option.configs.wanStauts.gateway);
                if(typeof(S.option.configs.wanStauts.dns) != "undefined")$("#network_static_dns1").val(S.option.configs.wanStauts.dns[0]);
                if(typeof(S.option.configs.wanStauts.dns) != "undefined" && S.option.configs.wanStauts.dns.length>1)$("#network_static_dns2").val(S.option.configs.wanStauts.dns[1]);
            }else if(S.option.configs.wanStauts.proto == "pppoe"){
                var str = S.tools.heredoc(function(){
                    /*
                     <div class="con">
                     <div class="con_li"></div>
                     <div class="con_li">
                     <span>连接类型：</span>
                     <b>
                     <select id="wan_proto" style="height:30px; margin-top:5px; width:200px;">
                     <option value="static" >静态IP(手动获取)</option>
                     <option value="dhcp" >自动获取IP(DHCP)</option>
                     <option value="pppoe" selected="selected">PPPOE(虚拟拨号)</option>
                     </select>
                     </b>
                     </div>
                     <div id="wanStauts_content">
                     <div class="con_li">
                     <span>帐号：</span>
                     <b>
                     <input type="text" name="pppoe_user" id="pppoe_user" value="" />
                     </b>
                     </div>
                     <div class="con_li">
                         <span>密码：</span>
                         <b>
                            <input type="password" name="pppoe_password" id="pppoe_password" value="" />
                         </b>
                     </div>
                     </div>
                     <div class="con_li_b"><button id="settingbutton"><a href="javascript:;">保存</a></button></div>
                     */
                });
                $('#content').html(str);
                if(typeof(S.option.configs.wanStauts.username) != "undefined") $("#pppoe_user").val(S.option.configs.wanStauts.username);
                if(typeof(S.option.configs.wanStauts.password) != "undefined") $("#pppoe_password").val(S.option.configs.wanStauts.password);
            }

            S.regEvent.doNetworkEvent();

            $("#settingbutton").click(function(){
                S.isLogout();
                S.onReadre.setNet();
            });

        },
        bar:function(){
            var str = S.tools.heredoc(function(){
                /*
                 <div class="top">
                     <img src="resource/img/logo.png">
                     <span>模块设置</span>
                     <b id="timess"></b>
                 </div>
                 <div  class="left">
                     <ul id="bars">
                         <li no="0" class="dq"><a href="javascript:;">当前状态</a></li>
                         <li no="1"><a href="javascript:;">网络设置</a></li>
                         <li no="2"><a href="javascript:;">无线设置</a></li>
                         <li no="3"><a href="javascript:;">互连设置</a></li>
                         <li no="4"><a href="javascript:;">密码修改</a></li>
                         <li no="5"><a href="javascript:;">退出</a></li>
                     </ul>
                 </div>
                     <div id="content" class="content">
                     </div>
                 */
            });
            $('body').html(str);
            S.dateFormat.setTimeInt();
            S.onReadre.bar();
        },
        setNetwork:function(proto){
            if(proto == "dhcp"){
                var str = '';
                var str = S.tools.heredoc(function(){
                    /*
                     */
                });
                $("#wanStauts_content").html(str);
            }else if(proto == "static"){
                var str = S.tools.heredoc(function(){
                    /*
                     <div class="con_li">
                     <span>IP地址：</span>
                     <b >
                     <input type="text" name="network_static_ip" id="network_static_ip" />
                     </b>
                     </div>
                     <div class="con_li">
                     <span>子网掩码：</span>
                     <b>
                     <input type="text" name="network_static_netmask" id="network_static_netmask" />
                     </b>
                     </div>
                     <div class="con_li">
                     <span>网关地址：</span>
                     <b >
                     <input type="text" name="network_static_gatewa" id="network_static_gatewa" />
                     </b>
                     </div>
                     <div class="con_li">
                     <span>首选dns：</span>
                     <b >
                     <input type="text" name="network_static_dns1" id="network_static_dns1" />
                     </b>
                     </div>
                     <div class="con_li">
                     <span>备用dns：</span>
                     <b >
                     <input type="text" name="network_static_dns2" id="network_static_dns2" />
                     </b>
                     </div>
                     */
                });
                $("#wanStauts_content").html(str);
                if(typeof(S.option.configs.wanStauts.ipaddr) != "undefined") $("#network_static_ip").val(S.option.configs.wanStauts.ipaddr);
                if(typeof(S.option.configs.wanStauts.netmask) != "undefined")$("#network_static_netmask").val(S.option.configs.wanStauts.netmask);
                if(typeof(S.option.configs.wanStauts.gateway) != "undefined")$("#network_static_gatewa").val(S.option.configs.wanStauts.gateway);
                if(typeof(S.option.configs.wanStauts.dns) != "undefined")$("#network_static_dns1").val(S.option.configs.wanStauts.dns[0]);
                if(typeof(S.option.configs.wanStauts.dns) != "undefined" && S.option.configs.wanStauts.dns.length>1)$("#network_static_dns2").val(S.option.configs.wanStauts.dns[1]);
            }else if(proto == "pppoe"){
                var str = S.tools.heredoc(function(){
                    /*
                     <div class="con_li">
                     <span>帐号：</span>
                     <b>
                     <input type="text" name="pppoe_user" id="pppoe_user" value="" />
                     </b>
                     </div>
                     <div class="con_li">
                     <span>密码：</span>
                     <b>
                     <input type="password" name="pppoe_password" id="pppoe_password" value="" />
                     </b>
                     </div>
                     */
                });
                $("#wanStauts_content").html(str);
                if(typeof(S.option.configs.wanStauts.username) != "undefined") $("#pppoe_user").val(S.option.configs.wanStauts.username);
                if(typeof(S.option.configs.wanStauts.password) != "undefined") $("#pppoe_password").val(S.option.configs.wanStauts.password);
            }

        },
        wifiSet:function(){
            if(S.option.configs.wifi_iface.disabled == 0){
                var str = S.tools.heredoc(function(){
                    /*
                     <div class="con_li">
                     <span>启用无线：</span>
                     <b>
                     <input type="checkbox" name="wifiset_status" id="wifiset_status" style="width:15px;height:15px" />
                     <button id="wifi_san" style="margin-left:20px;">扫描无线</button>
                     </b>
                     </div>
                     <div class="con_li">
                        <span>无线类型：</span>
                         <b>
                             <select id="wifiset_type" style="height:30px; margin-top:5px; width:200px;">
                                <option value="ap">无线访问点(ap)</option>
                                <option value="sta">客户端(client)</option>
                             </select>
                         </b>
                     </div>
                     <div id="wifiset_type_ap">
                     <div class="con_li">
                         <span>SSID：</span>
                         <b>
                            <input type="text" name="wifiset_ssid" id="wifiset_ssid" value="" />
                         </b>
                     </div>
                     <div class="con_li">
                         <span>加密方式：</span>
                         <b>
                             <select id="wifiset_modecode" style="height:30px; margin-top:5px; width:200px;">
                                 <option value="psk">WPA-PSK</option>
                                 <option value="psk2">WPA2-PSK</option>
                                 <option value="psk-mixed">WPA-PSK/WPA2-PSK Mixed Mode</option>
                             </select>
                         </b>
                     </div>
                     <div class="con_li">
                         <span>信道：</span>
                         <b>
                             <select id="wifiset_wifiRadio" style="height:30px; margin-top:5px; width:200px;">
                                 <option value="auto">auto</option>
                                 <option value="0">0</option>
                                 <option value="1">1</option>
                                 <option value="2">2</option>
                                 <option value="3">3</option>
                                 <option value="4">4</option>
                                 <option value="5">5</option>
                                 <option value="6">6</option>
                                 <option value="7">7</option>
                                 <option value="8">8</option>
                                 <option value="9">9</option>
                                 <option value="10">10</option>
                                 <option value="11">11</option>
                             </select>
                         </b>
                     </div>

                     <div class="con_li">
                         <span>算法：</span>
                         <b>
                             <select id="wifiset_cipher" style="height:30px; margin-top:5px; width:200px;">
                                 <option value="auto">自动</option>
                                 <option value="ccmp">强制使用CCMP(AES)加密</option>
                             </select>
                         </b>
                     </div>
                     <div class="con_li">
                         <span>密码：</span>
                         <b>
                            <input type="text" name="wifiset_key" id="wifiset_key" value="" />
                         </b>
                     </div>
                     </div>
                     <div id="wifiset_type_sta">
                     </div>
                     <div class="con_li_b" style="width:100%;"><button id="wifiset_button"><a href="javascript:;">保存</a></button></div>
                     <div style="width:100%;height:30px;clear:both;"></div>
                     <div id="scan_list" style="width: 60%;height:auto; margin-left: 20%;" >
                     </div>
                     */
                });
                $("#content").html(str);
                $("#wifiset_status").attr("checked", "checked");
                $('#wifiset_type option').each(function (i) {
                    if ($(this).attr("value") == S.option.configs.wifi_iface.mode) {
                        $(this).attr("selected", true);
                    } else {
                        $(this).attr("selected", false);
                    }
                });
                //wifiset_cipher
                S.option.configs.wifi_iface.encryptions = S.tools.parseEcn(S.option.configs.wifi_iface.encryption);
                $('#wifiset_modecode option').each(function (i) {
                    if ($(this).attr("value") == S.option.configs.wifi_iface.encryptions.encryption) {
                        $(this).attr("selected", true);
                    } else {
                        $(this).attr("selected", false);
                    }
                });
                $('#wifiset_wifiRadio option').each(function (i) {
                    if ($(this).attr("value") == S.option.configs.wifiRadio.channel) {
                        $(this).attr("selected", true);
                    }
                });
                $('#wifiset_cipher option').each(function (i) {
                    if ($(this).attr("value") == S.option.configs.wifi_iface.encryptions.ciphers) {
                        $(this).attr("selected", true);
                    } else {
                        $(this).attr("selected", false);
                    }
                });
                $("#wifiset_ssid").val(S.option.configs.ssid);
                $("#wifiset_key").val(S.option.configs.wifi_iface.key);
                $("#wifiset_button").click(function () {
                    var disabledss = $("#wifiset_status").is(':checked');
                    if(disabledss== true){
                        S.onReadre.setWifi();
                        setTimeout(function(){
                            location.reload(true);
//                            S.onReadre.focusbg();
//                            S.layout.wifiSet();
//                            $("#bars li").eq(2).addClass('dq');
                        },1000);
                    }else{
                        var lists = [];
                        var params = S.onReadre.list.setWifiConfig;
                        params.params[3].values = {};
                        params.params[3].values = {"disabled":1};
                        lists[0] = params;
                        S.onReadre.set(lists);
                        setTimeout(function(){
                            S.onReadre.focusbg();
                            S.layout.wifiSet();
                            $("#bars li").eq(2).addClass('dq');
                        },1000);
                    }
                });
                S.regEvent.doWifiSanEvent();
                S.regEvent.doWifiTypeEvent();
                if (S.option.configs.wifi_iface.mode == 'sta') {
                    $("#wifiset_type_ap").hide();
                    $("#wifiset_type_sta").show();
                    S.onReadre.setWifiModeSta();
                }
            }else{
                var str = S.tools.heredoc(function(){
                    /*
                     <div class="con_li">
                     <span>启用无线：</span>
                     <b>
                     <input type="checkbox" name="wifiset_status" id="wifiset_status_close" style="width:15px;height:15px" />
                     </b>
                     </div>
                     <div class="con_li_b" style="width:100%;"><button id="wifiset_button_close"><a href="javascript:;">保存</a></button></div>
                     <div style="width:100%;height:30px;clear:both;"></div>
                     <div id="scan_list" style="width: 60%;height:auto; margin-left: 20%;" >
                     </div>
                     */
                });
                $("#content").html(str);
                $("#wifiset_button_close").click(function(){
                    var disabledss = $("#wifiset_status_close").is(':checked');
                    if(disabledss== true){
                        var lists = [];
                        var params = S.onReadre.list.setWifiConfig;
                        params.params[3].values = {};
                        params.params[3].values = {"disabled":0};
                        lists[0] = params;
                        S.onReadre.set(lists);
                        setTimeout(function(){
                                S.onReadre.focusbg();
                                S.layout.wifiSet();
                            $("#bars li").eq(2).addClass('dq');
                        },1000);
                    }else{
                        var lists = [];
                        var params = S.onReadre.list.setWifiConfig;
                        params.params[3].values = {};
                        params.params[3].values = {"disabled":1};
                        lists[0] = params;
                        S.onReadre.set(lists);
                        setTimeout(function(){
                            S.onReadre.focusbg();
                            S.layout.wifiSet();
                            $("#bars li").eq(2).addClass('dq');
                        },1000);
                    }
                });
            }
        },
        hulian:function(){
            var str = S.tools.heredoc(function(){
                /*

                 <div class="con_li">
                     <span>配对设备ID：</span>
                     <b>
                     <input type="text" name="hulian_id" id="hulian_id" value="" />
                     </b>
                 </div>

                 <div class="con_li">
                     <span>互连密码：</span>
                     <b>
                        <input type="text" name="hulian_pass" id="hulian_pass" value="" />
                     </b>
                 </div>
                 <div class="con_li">
                 <span>MTU：</span>
                 <b>
                 <input type="text" name="hulian_mtu" id="hulian_mtu" value="" />
                 </b>
                 </div>

                 <div class="con_li">
                     <h3>提示：保存互连参数后系统将会自动重启</h3>
                 </div>
                 <div class="con_li_b"><button id="hulian_button"><a href="javascript:;">保存</a></button></div>
                 
                 */
            });
            $("#content").html(str);
            if(S.option.configs.routedif !== undefined){
                if(S.option.configs.routedif.remoteid !== undefined) $("#hulian_id").val(S.option.configs.routedif.remoteid);
                if(S.option.configs.routedif.remotepass !== undefined) $("#hulian_pass").val(S.option.configs.routedif.remotepass);
                if(S.option.configs.routedif.mtu !== undefined) $("#hulian_mtu").val(S.option.configs.routedif.mtu);
            }

            S.regEvent.doHulian();

           /// $("#rest").click(function(){
                //S.onReadre.reboot();
           // });
        },
        setbit:function(){
            var str = S.tools.heredoc(function(){
                /*

                 <div class="con_li">
                     <span>波特率：</span>
                         <b>
                             <select id="setbit_serialbaud" style="height:30px; margin-top:5px; width:200px;">
                                 <option value="2400">2400</option>
                                 <option value="4800">4800</option>
                                 <option value="9600">9600</option>
                                 <option value="14400">14400</option>
                                 <option value="19200">19200</option>
                                 <option value="38400">38400</option>
                                 <option value="56000">56000</option>
                                 <option value="57600">57600</option>
                                 <option value="115200">115200</option>

                             </select>
                     </b>
                 </div>
                 <div class="con_li">
                 <span>效验位：</span>
                 <b>
                 <select id="setbit_serialpaity" style="height:30px; margin-top:5px; width:200px;">
                 <option value="none">NONE</option>
                 <option value="odd">ODD</option>
                 <option value="even">EVEN</option>

                 </select>
                 </b>
                 </div>
                 <div class="con_li">
                 <span>数据位：</span>
                 <b>
                 <select id="setbit_serialdata" style="height:30px; margin-top:5px; width:200px;">
                 <option value="8">8</option>
                 <option value="7">7</option>
                 <option value="6">6</option>
                 <option value="5">5</option>

                 </select>
                 </b>
                 </div>
                 <div class="con_li">
                 <span>停止位：</span>
                 <b>
                 <select id="setbit_serialstop" style="height:30px; margin-top:5px; width:200px;">
                 <option value="1">1</option>
                 <option value="1.5">1.5</option>
                 <option value="2">2</option>

                 </select>
                 </b>
                 </div>
                 <div class="con_li_b"><button id="setbit_button"><a href="javascript:;">保存</a></button></div>

                 */
            });
            $("#content").html(str);
            if(S.option.configs.routedif !== undefined){
                $('#setbit_serialbaud option').each(function(i){
                    if(S.option.configs.routedif !== undefined && ($(this).attr("value") == S.option.configs.routedif.serialbaud)){
                        $(this).attr("selected",true);
                    }else{
                        $(this).attr("selected",false);
                    }
                });
                $('#setbit_serialdata option').each(function(i){
                    if($(this).attr("value") == S.option.configs.routedif.serialdata){
                        $(this).attr("selected",true);
                    }else{
                        $(this).attr("selected",false);
                    }
                });
                $('#setbit_serialstop option').each(function(i){
                    if($(this).attr("value") == S.option.configs.routedif.serialstop){
                        $(this).attr("selected",true);
                    }else{
                        $(this).attr("selected",false);
                    }
                });
                $('#setbit_serialpaity option').each(function(i){
                    if($(this).attr("value") == S.option.configs.routedif.serialpaity){
                        $(this).attr("selected",true);
                    }else{
                        $(this).attr("selected",false);
                    }
                });
            }
            S.regEvent.doSetBit();
        }

    };

    this.tools = {
        heredoc : function(fn){
            return fn.toString().replace(/\/\*/,'').replace(/\*\//,'').split('\n').slice(1,-1).join('\n') + '\n';
        },
        stopPropagation : function(event){
            if (event.stopPropagation) {
                event.stopPropagation();
            }else if (window.event) {
                window.event.cancelBubble = true;
            }
        },
        setCookie:function(name,valueg,time){
            var exp = new Date();
            exp.setTime(exp.getTime() + time);
            S.cookieUtil.set(name,valueg,exp.toGMTString());
        },
        parseEcn:function(str){
            var mstr = {encryption:'',ciphers:''};
            var cipher = [];
            var arr = str.split("+");
            for(var i in arr){
                if(i==0){
                    mstr.encryption = arr[i];
                }else{
                    cipher.push(arr[i]);
                }

            }
            if(cipher.length >0){
                if(cipher.length>1){
                    mstr.ciphers = cipher.join("+");
                }else{
                    mstr.ciphers = cipher[0];
                }
            }
            return mstr;
        },
        toMask:function(num){
            switch (num){
                case 8:
                    return '255.0.0.0';
                    break;
                case 9:
                    return '255.128.0.0';
                    break;
                case 10:
                    return '255.192.0.0';
                    break;
                case 11:
                    return '255.224.0.0';
                    break;
                case 12:
                    return '255.240.0.0';
                    break;
                case 13:
                    return '255.248.0.0';
                    break;
                case 14:
                    return '255.252.0.0';
                    break;
                case 15:
                    return '255.254.0.0';
                    break;
                case 16:
                    return '255.255.0.0';
                    break;
                case 17:
                    return '255.255.128.0';
                    break;
                case 18:
                    return '255.255.192.0';
                    break;
                case 19:
                    return '255.255.224.0';
                    break;
                case 20:
                    return '255.255.240.0';
                    break;
                case 21:
                    return '255.255.248.0';
                    break;
                case 22:
                    return '255.255.252.0';
                    break;
                case 23:
                    return '255.255.254.0';
                    break;
                case 24:
                    return '255.255.255.0';
                    break;
                case 25:
                    return '255.255.255.128';
                    break;
                case 26:
                    return '255.255.255.192';
                    break;
                case 27:
                    return '255.255.255.224';
                    break;
                case 28:
                    return '255.255.255.240';
                    break;
                case 29:
                    return '255.255.255.248';
                    break;
                case 30:
                    return '255.255.255.252';
                    break;
                default :
                    return '';
                    break;
            }
        }

    };

    this.dateFormat = {
        setTime:function(){
            var str = "-";
            var str1 = ":";
            var z = '';
            var date = new Date();
            var year = date.getFullYear();
            var mon = date.getMonth();
            if((mon+1)<10){
                mon = "0"+(mon+1);
            }else{
                mon = (mon+1);
            }
            var da = date.getDate();
            if(da <10) da = "0"+da;
            var meek = date.getDay();
            var h=date.getHours();
            var m=date.getMinutes();
            var mir = date.getUTCSeconds();
            if(h<10) h = "0"+h;
            if(m<10){
                m = "0"+m;
            }
            if(mir<10) mir = "0"+mir;
            z = year+'年'+mon+'月'+da+"日 "+this.weekArray[meek]+' '+h+str1+m+str1+mir;
            $("#timess").html(z);
        },
        setTimeInt:function(){
            var base = this;
            setInterval(function(){
                base.setTime();
            },1000);
        },
        weekArray:['星期日','星期一','星期二','星期三','星期四','星期五','星期六']
    };

    this.onClall = {
        _doGetWlanMac:function(data){
            if(data){
                S.option.configs.wlan = data.result[1];
            }
        },
        _doGetUser:function(data){
            if(data){
                S.option.configs.username = data.result[1].value;
            }
        },
        _dogGetLan:function(data){
            if(typeof data.result != undefined && typeof data.result != "undefined"){
                S.option.configs.lan = data.result[1].values;
                if(S.onReadre.index == 0){
                    $("#lan_ip").html(S.option.configs.lan.ipaddr);
                 //   $("#mac").html(S.option.configs.lan.macaddr);
                }
            }
        },
        _doGetOdhcpd:function(data){
            if(data){
                if(typeof(data.result[1]) == undefined || typeof(data.result[1]) == "undefined"){
                    S.option.configs.odhcpd = 1;
                }else{
                    S.option.configs.odhcpd = data.result[1].value;
                }
                if(S.onReadre.index == 0){
                    if(S.option.configs.odhcpd == 1){
                        $("#dhcp_state").html('开启');
                    }else{
                        $("#dhcp_state").html('关闭');
                    }
                }
            }
        },
        _doGetWifiSta:function(data){
            if(data){
                S.option.configs.wifi_iface = data.result[1].values;
                S.option.configs.wifi_iface.disabled = S.option.configs.disabled = data.result[1].values.disabled == undefined || data.result[1].values.disabled == 0 || data.result[1].values.disabled == "0" ? 0 : 1;
                S.option.configs.encryption = data.result[1].values.encryption;
                S.option.configs.ssid = data.result[1].values.ssid;
                if(S.onReadre.index == 0){
                    $("#ssid").html(S.option.configs.ssid);
                    $("#wifi_passwd").html(S.option.configs.wifi_iface.key);
                    if(S.option.configs.wifi_iface.disabled == 0){
				if(S.option.configs.wifi_iface.mode == 'sta'){
                        $("#wifi_status").html('客户端(client)');}else{$("#wifi_status").html('无线访问点(AP)');}
                    }else{
                        $("#wifi_status").html('关闭');
				
                    }
                }
            }
        },
        _doGetSerial:function(data){
            if(data){
                if(data.result[1] !== undefined){
                    option.configs.routedif = data.result[1].values;
                    if(S.onReadre.index == 0){
                        $("#baudrate").html(S.option.configs.routedif.serialbaud);
                        $("#databit").html(S.option.configs.routedif.serialdata);
                        $("#stopbit").html(S.option.configs.routedif.serialstop);
                        $("#checkbit").html(S.option.configs.routedif.serialpaity);
                        $("#rotu_name").html(S.option.configs.routedif.name);
				        $("#hulian_id").html(S.option.configs.routedif.remoteid);
                        if(S.option.configs.routedif.interconnect ==0){
                            $("#hlzts").html('未连接');
                        }else if(S.option.configs.routedif.interconnect ==1){
                            $("#hlzts").html('已连接');
                        }
                    }
                }
            }
        },
        _doGetWifiRadio:function(data){
            if(data){
                S.option.configs.wifiRadio = data.result[1].values;
            }
        },
        _doGetBit:function(data){

        },
        _doGetHostName:function(data){
            if(data){
                S.option.configs.hostname = data.result[1].value;
                if(S.onReadre.index == 0){
                    $("#rotu_name").html(S.option.configs.hostname);
                }
            }
        },
        _doGetWlanStatus:function(data){
            if(data){
                if(typeof data.result != undefined && typeof data.result != "undefined"){
                    S.option.configs.wanStauts = data.result[1].values;
                    /*
                    $("#wan_state").html(S.option.configs.wanStauts.proto);
                    var str ='';
                    if(S.option.configs.wanStauts.proto == "static"){
				str += ' <div class="con_li"><span>WAN口IP：</span><b >'+S.option.configs.wanStauts.ipaddr+'</b></div>';
                       str += ' <div class="con_li"><span>WAN口网关：</span><b >'+S.option.configs.wanStauts.gateway+'</b></div>';
                        
                        if(S.option.configs.wanStauts.dns[0] == undefined) S.option.configs.wanStauts.dns[0] ="";
                        if(S.option.configs.wanStauts.dns[1] == undefined) S.option.configs.wanStauts.dns[1] ="";
                        str += ' <div class="con_li"><span>WAN口dns1：</span><b >'+S.option.configs.wanStauts.dns[0]+'</b></div>';
                        str += ' <div class="con_li"><span>WAN口dns2：</span><b >'+S.option.configs.wanStauts.dns[1]+'</b></div>';
                    }else if(S.option.configs.wanStauts.proto == "dhcp"){
                        try{
                            if(S.option.configs.wanStauts.gateway !== undefined) {
                                str += ' <div class="con_li"><span>WAN口网关：</span><b >'+S.option.configs.wanStauts.gateway+'</b></div>';
                            }else{
                                str += ' <div class="con_li"><span>WAN口网关：</span><b ></b></div>';
                            }
                        }catch (e){

                            console.log(e);
                        }
                        try{
                            if(S.option.configs.wanStauts.ipaddr !== undefined){
                                str += ' <div class="con_li"><span>WAN口IP：</span><b >'+S.option.configs.wanStauts.ipaddr+'</b></div>';
                            }else{
                                str += ' <div class="con_li"><span>WAN口IP：</span><b ></b></div>';
                            }
                        }catch (e){

                            console.log(e);
                        }
                        try{
                           ;
                            }
                        }catch (e){
                            console.log(e);
                        }
                        try{
                        ;
                            }
                        }catch (e){

                            console.log(e);
                        }
                        try{
                            if(S.option.configs.wanStauts.dns !== undefined) {
					
                                if(S.option.configs.wanStauts.dns[0] == undefined) S.option.configs.wanStauts.dns[0] ="";
                                if(S.option.configs.wanStauts.dns[1] == undefined) S.option.configs.wanStauts.dns[1] ="";
                                str += ' <div class="con_li"><span>WAN口dns1：</span><b >'+S.option.configs.wanStauts.dns[0]+'</b></div>';
                                str += ' <div class="con_li"><span>WAN口dns2：</span><b >'+S.option.configs.wanStauts.dns[1]+'</b></div>';
                            }else{
                                str += ' <div class="con_li"><span>WAN口dns1：</span><b ></b></div>';
                                str += ' <div class="con_li"><span>WAN口dns2：</span><b ></b></div>';
                            }

                        }catch (e){
                            console.log(e);
                        }
                        $("#wan_state_waninfos").html(str);
                    }
                    */
                }
            }
        },
        _doGetWanStatus:function(data){
            if(data.result !== undefined){


		if(data.result[1].proto=="static")
			{
				 $("#wan_state").html("静态地址");
			}
			if(data.result[1].proto=="dhcp")
			{
				 $("#wan_state").html("动态获取(DHCP)");
			}
			if(data.result[1].proto=="pppoe")
			{
				 $("#wan_state").html("PPPOE拨号");
			}

                if(data.result[1].up == true){
                    var result = data.result[1];
                    S.option.wanStauts = {
                        up:true,
                        proto:result.proto,
                        gateway:result.route[0].nexthop,
                        ipaddr:result["ipv4-address"][0].address,
                        netmask: S.tools.toMask(result["ipv4-address"][0].mask)
                    };
                    //                        dns1:result.dns-server[0],
                    //dns2:result.dns-server[1],
                    S.option.wanStauts.dns = [];
                    if(result["dns-server"][0] !== undefined){

					S.option.wanStauts.dns[0] = result["dns-server"][0];	
                    }else{S.option.wanStauts.dns[0] = 'null';}
                    if(result["dns-server"][1] !== undefined){
                        S.option.wanStauts.dns[1] = result["dns-server"][1];
                    }else{S.option.wanStauts.dns[1] = 'null';}
                }else{
                    S.option.wanStauts = {
                        up:false,
                        proto:'',
                        gateway:'',
                        ipaddr:'',
                        netmask: '',
                        dns:['','']
                    };
                }
            }else{
                S.option.wanStauts = {
                    up:false,
                    proto:'',
                    gateway:'',
                    ipaddr:'',
                    netmask: '',
                    dns:['','']
                };
            }
            var str = '';
 		str += ' <div class="con_li"><span>WAN口IP：</span><b >'+S.option.wanStauts.ipaddr+'</b></div>';
            str += ' <div class="con_li"><span>WAN口网关：</span><b >'+S.option.wanStauts.gateway+'</b></div>';
           
		if(S.option.wanStauts.dns[0]!=="null")
            {str += ' <div class="con_li"><span>WAN口dns1：</span><b >'+S.option.wanStauts.dns[0]+'</b></div>';
		if(S.option.wanStauts.dns[1]!=="null")
            str += ' <div class="con_li"><span>WAN口dns2：</span><b >'+S.option.wanStauts.dns[1]+'</b></div>';}
 $("#mac").html(S.option.configs.wanStauts.macaddr);
          //  $("#wan_state").html(S.option.wanStauts.proto);
            
			if(S.option.wanStauts.proto=="static")
			{
				 $("#wan_state").html("静态地址");
			}
			if(S.option.wanStauts.proto=="dhcp")
			{
				 $("#wan_state").html("动态获取(DHCP)");
			}
			if(S.option.wanStauts.proto=="pppoe")
			{
				 $("#wan_state").html("PPPOE拨号");
			}

$("#wan_state_waninfos").html(str);
        },
        _doGetWwanStatus:function(data){
            if(data.result !== undefined){
                if(data.result[1].up == true){
                    var result = data.result[1];
                    S.option.WwanStauts = {
                        up:true,
                        proto:result.proto,
                        gateway:result.route[0].nexthop,
                        ipaddr:result["ipv4-address"][0].address,
                        netmask: S.tools.toMask(result["ipv4-address"][0].mask)
                    };
                    //                        dns1:result.dns-server[0],
                    //dns2:result.dns-server[1],
                    S.option.WwanStauts.dns = [];
                    if(result["dns-server"][0] !== undefined){
                        S.option.WwanStauts.dns[0] = result["dns-server"][0];
                    }else{S.option.WwanStauts.dns[0] = 'null';}
                    if(result["dns-server"][1] !== undefined){
                        S.option.WwanStauts.dns[1] = result["dns-server"][1];
                    }else{S.option.WwanStauts.dns[1] = 'null';}
                }else{
                    S.option.WwanStauts = {
                        up:false,
                        proto:'',
                        gateway:'',
                        ipaddr:'',
                        netmask: '',
                        dns:['','']
                    };
                }
            }else{
                S.option.WwanStauts = {
                    up:false,
                    proto:'',
                    gateway:'',
                    ipaddr:'',
                    netmask: '',
                    dns:['','']
                };
            }

			//	</div>
         //    <div class="con">
         	var str='';    
            str += '<h3>无线WAN口状态：(提示：当无线为客户端模式时有效)</h3>';
            str += ' <div class="con_li"><span>WWAN口IP：</span><b >'+S.option.WwanStauts.ipaddr+'</b></div>';
  		str += ' <div class="con_li"><span>WWAN口网关：</span><b >'+S.option.WwanStauts.gateway+'</b></div>';

            $("#wwan_state").html(S.option.wanStauts.proto);
		if(S.option.configs.wifi_iface.disabled == 0){
			if(S.option.configs.wifi_iface.mode == 'sta'){
           			 $("#wwan_state_wwaninfos").html(str);}
		}
        },
        _doCommitNetwork:function(){
            S.getId();
            var reg =
                {
                    id: S.id,
                    jsonrpc:'2.0',
                    method:"call",
                    params:[S.option.sid,'uci','commit',{config:'network'}]
                };
            S._call(reg,function(data){
                var lists = [
                    S.onReadre.list.WlanStatus
                ];
                S.onReadre.get(lists);
            });
        },
        _doCommitFirewall:function(){
            S.getId();
            var reg =
            {
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'uci','commit',{config:'firewall'}]
            };
            S._call(reg,function(data){
//                var lists = [
//                    S.onReadre.list.wifi
//                ];
//                S.onReadre.get(lists);
            });
        },
        _doCommitWireless:function(){
            S.getId();
            var reg =
            {
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'uci','commit',{config:'wireless'}]
            };
            S._call(reg,function(data){
                var lists = [
                    S.onReadre.list.wifi
                ];
                S.onReadre.get(lists);
            });
        },
        _doScanWifi:function(data){
            if(data){
                var list = S.option.configs.wifi_List = data.result[1].results;
                var str = '';
                for(var i in list){
                    str += '<div style="width: 100%;height: 32px;">'
                    if(list[i].signal>=-40){
                        str += '<span style="width: 32px;height: 32px;overflow:hidden;background: url(resource/img/signal.png) no-repeat -141px 2px;"></span>';
                    }else if(list[i].signal>=-60){
                        str += '<span style="width: 32px;height: 32px;overflow:hidden;background: url(resource/img/signal.png) no-repeat -106px 2px;"></span>';
                    }else if(list[i].signal>=-80){
                        str += '<span style="width: 32px;height: 32px;overflow:hidden;background: url(resource/img/signal.png) no-repeat -71px 2px;"></span>';
                    }else if(list[i].signal>=-90){
                        str += '<span style="width: 32px;height: 32px;overflow:hidden;background: url(resource/img/signal.png) no-repeat -36px 2px;"></span>';
                    }else if(list[i].signal<=-90){
                        str += '<span style="width: 32px;height: 32px;overflow:hidden;background: url(resource/img/signal.png) no-repeat 1px 2px;"></span>';
                    }
                    if((typeof (list[i].bssid) != undefined) && (typeof (list[i].bssid) != "undefined") && (typeof (list[i].bssid) != null)){
                        str += '<span>&nbsp;&nbsp;Bssid:'+list[i].bssid+'</span>';
                    }
                    if(parseInt(list[i].channel)>=10){
                        str += '<span>&nbsp;&nbsp;Channel:'+list[i].channel+'</span>';
                    }else{
                        str += '<span>&nbsp;&nbsp;Channel:'+list[i].channel+'&nbsp;</span>';
                    }

                    //str += '<span>&nbsp;&nbsp;Mode:'+list[i].mode+'</span>';
                    str += '<span>&nbsp;&nbsp;ssid:'+list[i].ssid+'</span>';
                    str += '<span style="float:right;"><button  no="'+i+'" class="add_wifi_set" >加入网路</button></span>';
                    str += '</div> ';
                }
                $("#scan_list").html(str);
                S.regEvent.doAddWifiSet();
            }
        },
        _doCommitHulian:function(){
            S.getId();
            var reg =
            {
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'uci','commit',{config:'routedif'}]
            };
            S._call(reg,function(data){
                var lists = [
                    S.onReadre.list.serial
                ];
                S.onReadre.get(lists);
            });
        }
    };


    this.onReadre = {
        index:0,
        sid:null,
        list:{
            reboot:{
                params:['0','luci2.system','reboot','{}']
            },
            restart:{
                params:['0','luci2.system','init_action',{name:"",action:""}]
            },
            wlanMac:{
                params:['0','iwinfo','info',{device:"wlan0"}],
                callback: S.onClall._doGetWlanMac
            },
            user:{
                params:['0','uci','get',{config:'rpcd',section:'@login[0]',option:'username'}],
                callback: S.onClall._doGetUser
            },
            lan:{
                params:['0','uci','get',{config:'network',section:'lan'}],
                callback: S.onClall._dogGetLan
            },
            setStaNetworkwwan:{
                //params:['0','uci','set',{config:'network',section:""}]
                //params:['0','uci','set',{config:'network',section:"wwan",values:"interface"}]
                params:['0','uci','add',{config:'network',type:'interface',values:{'proto':'dhcp'}}],
                callback: S.onClall._doCommitNetwork
            },
            setStaNetwork:{
                params:['0','uci','set',{config:'network',section:''}],
                //_doCommitFirewall
                callback: S.onClall._doCommitNetwork
            },
            setFirewall:{
                params:['0','uci','set',{config:'firewall',section:'@zone[0]'}],
                callback: S.onClall._doCommitFirewall
            },
            delStaWifiOption:{
                params:['0','uci','delete',{config:'wireless',section:'@wifi-iface[0]'}],
                callback: S.onClall._doCommitWireless
            },
            odhcpd:{
                params:['0','uci','get',{config:'dhcp',section:'lan',option:'dynamicdhcp'}],
                callback: S.onClall._doGetOdhcpd
            },
            wifi:{
                params:['0','uci','get',{config:'wireless',section:'@wifi-iface[0]'}],
                callback: S.onClall._doGetWifiSta
            },
            wifiRadio:{
                params:['0','uci','get',{config:'wireless',section:'radio0'}],
                callback: S.onClall._doGetWifiRadio
            },
            serial:{
                params:['0','uci','get',{config:'routedif',section:'@routedif[0]'}],
                callback: S.onClall._doGetSerial
            },
            scanWifi:{
                //ubus call iwinfo scan '{"device":"wlan0"}'
                params:['0','iwinfo','scan',{"device":'wlan0'}],
                callback: S.onClall._doScanWifi
            },
            bit:{
                params:['0','uci','get',{config:'bit',section:'@bit[0]'}],
                callback: S.onClall._doGetBit
            },
//            hostname:{
//                params:['0','uci','get',{config:'system',section:'@system[0]',option:'hostname'}],
//                callback: S.onClall._doGetHostName
//            },
            WlanStatus:{
                params:['0','uci','get',{config:'network',section:'wan'}],
                callback: S.onClall._doGetWlanStatus
            },
            WanNetworkStatus:{
                params:['0','network.interface.wan','status',{}],
                callback: S.onClall._doGetWanStatus
            },
            WwanNetworkStatus:{
                params:['0','network.interface.wwan','status',{}],
                callback: S.onClall._doGetWwanStatus
            },
            commit_wan_dhcp:{
                params:['0','uci','set',{config:'network',section:'wan'}],
                callback: S.onClall._doCommitNetwork
            },
            setWifiConfig:{
                params:['0','uci','set',{config:'wireless',section:'@wifi-iface[0]'}],
                callback: S.onClall._doCommitWireless
            },
            setWifiConfigRadio:{
                params:['0','uci','set',{config:'wireless',section:'radio0'}],
                callback: S.onClall._doCommitWireless
            },
            hulian:{
                params:['0','uci','set',{config:'routedif',section:'@routedif[0]'}],
                callback: S.onClall._doCommitHulian
            },
//            commit_wireless:{
//                params:['0','uci','commit',{config:'wireless'}]
//            },
//            commit_network:{
//                params:['0','uci','commit',{config:'network'}]
//            },
//            commit_system:{
//                params:['0','uci','commit',{config:'system'}]
//            },
            delte_network_option:{
                params:['0','uci','delete',{config:'network',section:'wan'}]
            }
        },
        bar:function(){
            S.isLogout();
            var obj = $("#bars li");
            var base = this;
            //当前状态
            obj.eq(0).click(function(){
                S.isLogout();
                //base.getSerial();
                if(base.index == 0) return;
                S.layout.show();
                S.onReadre.focusbg();
                $(this).addClass('dq');
                base.index = 0;
		     //setTimeout('S.myrefresh()',3000);
            });
            //网络设置
            obj.eq(1).click(function(){
                S.isLogout();
                if(base.index ==1) return;
                S.layout.setting();
                S.onReadre.focusbg();
                $(this).addClass('dq');
                base.index = 1;
            });
            //无线设置
            obj.eq(2).click(function(){
                S.isLogout();
                if(base.index ==2) return;
                S.onReadre.focusbg();
                S.layout.wifiSet();
                base.index = 2;
                $(this).addClass('dq');
            });
            //互联设置
            obj.eq(3).click(function(){
                S.isLogout();
                if(base.index ==3) return;
                S.onReadre.focusbg();
                S.layout.hulian();
                base.index = 3;
                $(this).addClass('dq');
            });
            //系统设置
            obj.eq(4).click(function(){
                S.isLogout();
                if(base.index ==4) return;
                S.layout.setpass();
                S.onReadre.focusbg();
                $(this).addClass('dq');
                base.index = 4;
            });
            //退出
            obj.eq(5).click(function(){
                S.isLogout();
                S.onReadre.logout();
                S.onReadre.focusbg();
                $(this).addClass('dq');
            });


        },
        reboot:function(){
//            var lists = [];
//            var params = this.list.reboot;
//            lists[0] = params;
//            S.onReadre.set(lists);
            S.getId();
            var reg ={
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'luci2.system','reboot',{}]
            };
            S._call(reg,function(data){
            });
        },
        focusbg:function(){
            $("#bars li").removeClass('dq');
        },
        loginCheck:function(){
            $("input").each(function(i){
                if($.trim($(this).val()) == ''){
                    $(this).focus();
                    alert('不能为空');
                    return false;

                }
            });
        },
        logout:function(){
            S.start = true;
            var reg ={
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'session','destroy',{session: S.option.sid}]
            };
            S._call(reg,function(data){});
            S.option = {};
            S.cookieUtil.unset('sid');
            location.reload(true);
        },
        login:function(){
            S.getId();
            var name = $('#username').val();
            var pa = $("#passm").val();
            var reg ={
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[ '00000000000000000000000000000000','session','login',{username:name,password:pa}]
            };

            $.ajax('/ubus', {
                cache:       false,
                contentType: 'application/json',
                data:        JSON.stringify(reg),
                dataType:    'json',
                type:        'POST',
                timeout:     S.default.timeout,
                _rpc_req:   reg,
                error:function(){
                    alert("登录失败");
                },
                async:false,
                success:function(data){
                    if(data){
                        if(typeof data.result != undefined && typeof data.result != "undefined"){
                            if(data.result[0] == 0){
                                S.tools.setCookie('isLogin', 1);
                                var returndata = data.result[1];
                                S.option.sid = returndata.ubus_rpc_session;
                                S.option.isLogin = true;
                                S.setIntval();
                                S.tools.setCookie('sid',returndata.ubus_rpc_session,S.option.timeout);
                                S.layout.bar();
                                S.layout.show();
                            }else{
                                S.onReadre.logout();
                            }

                        }else{
                            S.onReadre.logout();
                        }

                    }else{
                        S.onReadre.logout();
                    }
                }
            });

//            S._call(reg,function(data){
//                if(data){
//                    if(typeof data.result != undefined && typeof data.result != "undefined"){
//                        if(data.result[0] == 0){
//                            console.log(data);
//                            S.tools.setCookie('isLogin', 1);
//                            var returndata = data.result[1];
//                            S.option.sid = returndata.ubus_rpc_session;
//                            S.option.isLogin = true;
//                            S.setIntval();
//                            S.tools.setCookie('sid',returndata.ubus_rpc_session,S.option.timeout);
//                            S.layout.bar();
//                            S.layout.show();
//                        }else{
//                            S.onReadre.logout();
//                        }
//
//                    }else{
//                        S.onReadre.logout();
//                    }
//
//                }else{
//                    S.onReadre.logout();
//                }
//            });
        },
        get:function(list){
            if(list.length>0){
                var regs =[];
                for(var ii=0;ii<list.length;ii++){
                    S.getId();
                    if(list[ii].params[0] == '0') list[ii].params[0] = S.option.sid;
                    regs.push({
                        id: S.id,
                        jsonrpc:'2.0',
                        method:"call",
                        params:list[ii].params
                    });
                }
                S._call(regs,function(data){
                    if(data){
                        for(var i=0;i<data.length;i++){
                            if(typeof (list[i].callback) != "undefined" && list[i].callback != undefined){
                                list[i].callback(data[i]);
                            }
                        }
                    }
                });
            }
        },
        set:function(list){
            if(list.length>0){
                var regs =[];
                for(var ii=0;ii<list.length;ii++){
                    S.getId();
                    if(list[ii].params[0] == '0') list[ii].params[0] = S.option.sid;
                    regs.push({
                        id: S.id,
                        jsonrpc:'2.0',
                        method:"call",
                        params:list[ii].params
                    });
                }
                S._call(regs,function(data){
                    if(data){
                        for(var i=0;i<data.length;i++){
                            if(typeof (list[i].callback) != "undefined" && list[i].callback != undefined){
                                list[i].callback(data[i]);
                            }
                        }
                    }
                });
            }
        },
        init:function(){
            this.sid = S.option.sid;
            var lists = [
                this.list.wlanMac,
                this.list.user,
                this.list.lan,
                this.list.odhcpd,
                this.list.wifi,
                this.list.wifiRadio,
                this.list.serial,
                this.list.bit,
                this.list.WlanStatus,
                this.list.WanNetworkStatus,
                this.list.WwanNetworkStatus
            ];
            this.get(lists);

        },
        setNet:function(){
            S.isLogout();
            var lists = [];
            var proto = $("#wan_proto").val();
            var params = {};
            var del = {};
            params = this.list.commit_wan_dhcp;
            del = this.list.delte_network_option;
         //   if(proto==S.option.configs.wanStauts.proto) return;
            switch (proto){
                case 'dhcp':
                        params.params[3].values = {};
                        del.params[3].options = {};
                        params.params[3].values = {proto:'dhcp'};
                        del.params[3].options = ['ipaddr','netmask','gateway','dns','username','password'];
                        lists[0] = params;
                        lists[1] = del;
                    break;
                case 'static':
                        var ip = $("#network_static_ip").val();
                        var netmasks = $("#network_static_netmask").val();
                        var gatewas = $("#network_static_gatewa").val();
                        var dns1 = $("#network_static_dns1").val();
                        var dns2 = $("#network_static_dns2").val();
                        params.params[3].values = {};
                        del.params[3].options = {};
                        params.params[3].values = {proto:'static',ipaddr:ip,netmask:netmasks,gateway:gatewas,dns:[dns1,dns2]};
                        del.params[3].options = [,'username','password'];
                        lists[0] = params;
                        lists[1] = del;
                    break;
                case 'pppoe':
                        var name = $("#pppoe_user").val();
                        var pass = $("#pppoe_password").val();
                        params.params[3].values = {};
                        del.params[3].options = {};
                        params.params[3].values = {proto:'pppoe',username:name,password:pass};
                        del.params[3].options = ['ipaddr','netmask','gateway','dns'];
                        lists[0] = params;
                        lists[1] = del;
                    break;
            }
            S.onReadre.set(lists);

        },
        setpm:function(){
            S.isLogout();
            var spd = $.trim($("#spd").val());
            var rspd = $.trim($("#rspd").val());
            if(spd !="" && spd.length >0){
                if(spd.length<8){
                    alert("密码必须大于8位");
                    return;
                }
                if(spd != rspd){
                    alert("密码错误");
                    return;
                }
                var reg ={
                    id: S.id,
                    jsonrpc:'2.0',
                    method:"call",
                    params:[S.option.sid,'luci2.system','password_set',{user: S.option.configs.username,password:spd}]
                };
                S._call(reg,function(data){
                    S.onReadre.logout();
                });
            }else{
                alert("密码错误");
                return;
            }
        },
        setWifi:function(){
            S.isLogout();

            var types = $("#wifiset_type").val();
            if( types== "ap"){
                var disabled = 0;
                var disabledss = $("#wifiset_status").is(':checked');
                if(disabledss== false){
                    var disabled = 1;
                }
                var mode = $('#wifiset_type').val();
                var encryption =  $('#wifiset_modecode').val();
                var scpher = $('#wifiset_cipher').val();
                if(scpher != undefined && scpher != ""){
                    encryption += '+'+scpher;
                }
                var ssid =  $("#wifiset_ssid").val();
                var key =  $("#wifiset_key").val();
                var channel = $("#wifiset_wifiRadio").val();


                var lists = [];
                var params = {};
                var params = this.list.setWifiConfig;
                params.params[3].values = {};
                params.params[3].values = {"disabled":disabled,"mode":mode,"encryption":encryption,"ssid":ssid,"key":key,'network':'lan'};
                lists[0] = params;
                var par = this.list.setWifiConfigRadio;
                par.params[3].values = {};
                par.params[3].values = {"channel":channel};
                lists[1] = par;
                S.onReadre.set(lists);
                S.onReadre.set(lists);
                var dles = [];
                var del = this.list.delStaWifiOption;
                del.params[3].options = ['bssid'];
                dles[0] = del;
                var mss = this.list.restart;
                mss.params[3].name = "network";
                mss.params[3].action = "restart";
                dles[1] = mss;
                S.onReadre.set(dles);
            }else if(types == "sta"){
                var ssid = $('#wifiset_type_sta_essid').val();
                var bssid = $('#wifiset_type_sta_bssid').val();
                var key = $('#wifiset_type_sta_key').val();
                var network = $('#wifiset_type_sta_network').val();
                var encryption = $('#wifiset_type_sta_encryption').val();
                var channel = $('#wifiset_type_sta_channel').val();
                var lists = [];
                var params = {};
                var params = this.list.setWifiConfig;
                params.params[3].values = {};
                params.params[3].values = {"ssid":ssid,"bssid":bssid,"encryption":encryption,"network":network,"key":key,"mode":"sta"};
                lists[0] = params;
                var par = this.list.setWifiConfigRadio;
                par.params[3].values = {};
                par.params[3].values = {"channel":channel};
                lists[1] = par;
                S.onReadre.set(lists);
                var mlist = [];
                var lmm = this.list.setStaNetworkwwan;
                lmm.params[3].name = network;
                mlist[0] = lmm;
                S.onReadre.set(mlist);
                var ls =[];
                var zone = this.list.setFirewall;
                zone.params[3].values = {};
                zone.params[3].values = {"network":"lan"};
                ls[0] = zone;
                //S.onReadre.set(zone);
                zone.params[3].section = '@zone[1]';
                zone.params[3].values = {"network":"wan wan6 "+network};
                ls[1] = zone;
                var mss = this.list.restart;
                mss.params[3].name = "network";
                mss.params[3].action = "restart";
                ls[2] = mss;
                S.onReadre.set(ls);
	              S.onReadre.reboot();
            }
        },
        setHulian:function(){
            S.isLogout();
            var id = $('#hulian_id').val();
            var pass =  $('#hulian_pass').val();
            var mtus = $('#hulian_mtu').val();
            var lists = [];
            var params = {};
            var params = this.list.hulian;
            params.params[3].values = {};
            params.params[3].values = {"remoteid":id,"remotepass":pass,"mtu":mtus};
            lists[0] = params;
            S.onReadre.set(lists);
        },
        SetBit:function(){
            S.isLogout();
            var serialbaud = $("#setbit_serialbaud").val();
            var serialdata = $("#setbit_serialdata").val();
            var serialstop = $("#setbit_serialstop").val();
            var serialpaity = $("#setbit_serialpaity").val();
            var lists = [];
            var params = {};
            var params = this.list.hulian;
            params.params[3].values = {};
            params.params[3].values = {"serialbaud":serialbaud,"serialdata":serialdata,"serialstop":serialstop,"serialpaity":serialpaity};
            lists[0] = params;
            S.onReadre.set(lists);
        },
        setWifiModeStaCM:function(){
            var str ='';
            str += '<div class="con_li"><span>ESSID：</span><b><input type="text" name="wifiset_type_sta_essid" id="wifiset_type_sta_essid" value="" /></b></div>';
            str += '<input type="hidden" name="wifiset_type_sta_bssid" id="wifiset_type_sta_bssid" value="" />';
            str += '<div class="con_li"><span>密码：</span><b><input type="text" name="wifiset_type_sta_key" id="wifiset_type_sta_key" value="" /></b></div>';
            str += '<input type="hidden" name="wifiset_type_sta_network" id="wifiset_type_sta_network" value="" />';
            str += '<input type="hidden" name="wifiset_type_sta_encryption" id="wifiset_type_sta_encryption" value="" />';
            str += '<input type="hidden" name="wifiset_type_sta_channel" id="wifiset_type_sta_channel" value="auto" />';
            //str += '<div class="con_li"><span>无线电功率：</span><b><input type="text" name="wifiset_type_sta_txpower" id="wifiset_type_sta_txpower" value="'+S.option.configs.wifi_List[no].txpower+'" /></b></div>';
		str += '<div class="con_li"><h3>提示1：保存无线客户端参数系统将会自动重启</h3></div>';
str += '<div class="con_li"><h3>提示2：使用客户端模式时WAN口不能插入网线</h3></div>';
            $("#wifiset_type_sta").html(str);
        },
        setWifiModeSta:function(){
            var str ='';
            str += '<div class="con_li"><span>ESSID：</span><b><input type="text" name="wifiset_type_sta_essid" id="wifiset_type_sta_essid" value="'+S.option.configs.wifi_iface.ssid+'" /></b></div>';
            str += '<input type="hidden" name="wifiset_type_sta_bssid" id="wifiset_type_sta_bssid" value="'+S.option.configs.wifi_iface.bssid+'" />';
            str += '<div class="con_li"><span>密码：</span><b><input type="text" name="wifiset_type_sta_key" id="wifiset_type_sta_key" value="'+S.option.configs.wifi_iface.key+'" /></b></div>';
            str += '<input type="hidden" name="wifiset_type_sta_network" id="wifiset_type_sta_network" value="'+S.option.configs.wifi_iface.network+'" />';
            str += '<input type="hidden" name="wifiset_type_sta_encryption" id="wifiset_type_sta_encryption" value="'+S.option.configs.wifi_iface.encryption+'" />';
            str += '<input type="hidden" name="wifiset_type_sta_channel" id="wifiset_type_sta_channel" value="'+S.option.configs.wifiRadio.channel+'" />';
            //str += '<div class="con_li"><span>无线电功率：</span><b><input type="text" name="wifiset_type_sta_txpower" id="wifiset_type_sta_txpower" value="'+S.option.configs.wifi_List[no].txpower+'" /></b></div>';
str += '<div class="con_li"><h3>提示1：保存无线客户端参数系统将会自动重启</h3></div>';
str += '<div class="con_li"><h3>提示2：使用客户端模式时WAN口不能插入网线</h3></div>';
            $("#wifiset_type_sta").html(str);
        }
    };

    this.regEvent =  {
        doLoginCheck:function(){
            $("#loginButton").click(function(event){
                //S.isLogout();
                S.tools.stopPropagation(event);
                S.onReadre.loginCheck();
                S.onReadre.login();
            });
        },
        doNetworkEvent:function(){
            $('#wan_proto').change(function(){
                S.isLogout();
                var proto = $(this).val();
                S.layout.setNetwork(proto);
            });
        },
        doWifiTypeEvent:function(){
            $("#wifiset_type").change(function(){
                var type = $(this).val();
                if(type == "ap"){
                    $("#wifiset_type_ap").show();
                    $("#wifiset_type_sta").hide();
                }else if(type == "sta"){
                    $("#wifiset_type_ap").hide();
                    if(S.option.configs.wifi_iface.mode == 'sta'){
                        S.onReadre.setWifiModeSta();
                    }else if(S.option.configs.wifi_iface.mode == 'ap'){
                        S.onReadre.setWifiModeStaCM();
                    }

                    $("#wifiset_type_sta").show();
                }
            });
        },
        doWifiSanEvent:function(){
            $('#wifi_san').click(function(){
                S.isLogout();
                //scan_list
                var lists = [
                    S.onReadre.list.scanWifi
                ];
                S.onReadre.get(lists);
            });
        },
        doHulian:function(){
            $('#hulian_button').click(function(){
                S.isLogout();
                S.onReadre.setHulian();
		    S.onReadre.reboot();
            });
        },
        doSetBit:function(){
            $('#setbit_button').click(function(){
                S.isLogout();
                S.onReadre.SetBit();
            });
        },
        doAddWifiSet:function(){
            $(".add_wifi_set").click(function(){
                S.isLogout();
                if($("#wifiset_type").val() == "sta"){
                    $("#wifiset_type_sta").empty();
                    var no = $(this).attr("no");
                    var wpa = S.option.configs.wifi_List[no].encryption.wpa;
                    var auth = S.option.configs.wifi_List[no].encryption.authentication;
                    if(auth.length == 1){
                        var en = auth[0];
                    }else if(auth.length > 1){
                        var en = auth.join("+");

                    }
			en='';
             if(wpa.length == 1 && (wpa[0] == 2 || wpa[1] == 2 )) {
                        en='psk2';

                    }
		else{en='psk';}
                    var auths = S.option.configs.wifi_List[no].encryption.ciphers;
                    if(auths.length == 1){
                        var ens = auths[0];
                    }else if(auths.length > 1){
                        var ens = auths.join("+");

                    }
                    var str ='';
                    str += '<div class="con_li"><span>ESSID：</span><b><input type="text" name="wifiset_type_sta_essid" id="wifiset_type_sta_essid" value="'+S.option.configs.wifi_List[no].ssid+'" /></b></div>';
                    str += '<input type="hidden" name="wifiset_type_sta_bssid" id="wifiset_type_sta_bssid" value="'+S.option.configs.wifi_List[no].bssid+'" />';
                    str += '<div class="con_li"><span>密码：</span><b><input type="text" name="wifiset_type_sta_key" id="wifiset_type_sta_key" value="" /></b></div>';
                    str += '<input type="hidden" name="wifiset_type_sta_network" id="wifiset_type_sta_network" value="wwan" />';
                    str += '<input type="hidden" name="wifiset_type_sta_encryption" id="wifiset_type_sta_encryption" value="'+en+'" />';
                    str += '<input type="hidden" name="wifiset_type_sta_channel" id="wifiset_type_sta_channel" value="'+S.option.configs.wifi_List[no].channel+'" />';
                    //str += '<div class="con_li"><span>无线电功率：</span><b><input type="text" name="wifiset_type_sta_txpower" id="wifiset_type_sta_txpower" value="'+S.option.configs.wifi_List[no].txpower+'" /></b></div>';
			str += '<div class="con_li"><h3>提示1：保存无线客户端参数系统将会自动重启</h3></div>';
			str += '<div class="con_li"><h3>提示2：使用客户端模式时WAN口不能插入网线</h3></div>';



                    $("#wifiset_type_sta").html(str);
                    //$("#wifiset_ssid").val(S.option.configs.wifi_List[no].ssid);
                }else{
                    alert("请设置无线类型");
                }
            });
        }
    };

    this.cookieUtil = {
        get:function(name){
            var cookieName = encodeURIComponent(name) + "=" ,
                cookieStart = document.cookie.indexOf(cookieName),
                cookieValue = null;
            if(cookieStart > -1){
                var cookieEnd = document.cookie.indexOf(";",cookieStart);
                if(cookieEnd == -1){
                    cookieEnd = document.cookie.length;
                }
                cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
            }
            return cookieValue;
        },
        set:function(name, value, expires, path, domain, secure){
            var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
            if(expires instanceof Date){
                cookieText += ";expires=" + expires.toGMTString();
            }
            if(path){
                cookieText += ";path=" + path;
            }
            if(domain){
                cookieText += ";domain=" + domain;
            }
            if(path){
                cookieText += ";secure=" + secure;
            }
            document.cookie = cookieText;
        },
        unset:function(name, path, domain, secure){
            this.set(name, "" , new Date(0), path, domain, secure);
        },
        checkCookie:function(name){
            var name=get(name);
            if (name!=null && name!=""){
                return name;
            }else{
                return false;
            }
        }
    };

}

